import { Component, Vue, Watch } from 'vue-property-decorator';
import style from '@/styles/views/room-list.module.less';
import viewsStyle from '@/styles/views/views.module.less';
import { EapLayout } from '@/components';
import {
  Button,
  Cell,
  CellGroup,
  Collapse,
  CollapseItem,
  Dialog,
  Field,
  Icon,
  NavBar,
  Popup,
  PullRefresh,
  RadioGroup,
  SwipeCell,
  Tab,
  Tabbar,
  TabbarItem,
  Tabs
} from 'vant';
import { ICreateRoomResp, IRoom } from '@/interfaces/api.interface';
import { IResponse } from '@/interfaces/common.interface';
import roomSvg from '@/assets/room.svg';
import Utils from '@/common/Utils';
import _ from 'lodash';

Vue.use(Dialog);

@Component({
  components: {
    'eap-layout': EapLayout,
    'van-nav-bar': NavBar,
    'van-button': Button,
    'van-tabs': Tabs,
    'van-tab': Tab,
    'van-collapse': Collapse,
    'van-collapse-item': CollapseItem,
    'van-radio-group': RadioGroup,
    'van-cell-group': CellGroup,
    'van-cell': Cell,
    'van-pull-refresh': PullRefresh,
    'van-field': Field,
    'van-popup': Popup,
    'van-swipe-cell': SwipeCell,
    'van-tabbar-item': TabbarItem,
    'van-tabbar': Tabbar,
    'van-icon': Icon
  },
  sockets: {
    connect() {
      // 说明是断线重连
      this.$socket.client.emit('init');
    }
  }
})
export default class RoomList extends Vue {
  private reloading = false;
  private isAddModel = false;
  private form = {
    creator: this.$store.state.accountInfo,
    name: ''
  };

  private get isManager() {
    const { managers, accountInfo } = this.$store.state;
    if (accountInfo.acoid) {
      return _.find(managers, { acoid: accountInfo.acoid });
    }
    return false;
  }

  @Watch('isManager')
  watchManager() {
    this.handleLongTag();
  }

  public created() {
    this.$socket.client.emit('init', ({ result, message }: IResponse) => {
      if (result) {
        this.$message.success(message);
      }
    });
  }

  public mounted() {
    this.handleLongTag();
  }

  private get rooms() {
    return this.$store.state.rooms || [];
  }

  public render() {
    return (
      <eap-layout>
        <van-nav-bar title='节能智控' slot='header' />
        {this.renderRoomList()}
        {this.renderAddRoomModel()}
      </eap-layout>
    );
  }

  private renderRoomList() {
    return (
      <div id='room-list' class={style['room-list']}>
        <div class={[style['room-item'], style['room-item-btn'], viewsStyle['touch']]} on-click={this.showAddModel}>
          <div class={style['room-item-content']}>
            <van-icon name='plus' size={28} color='#20a5df' />
          </div>
        </div>
        {this.rooms.map((item: IRoom) => {
          return (
            <div
              class={[style['room-item'], viewsStyle['touch']]}
              on-click={() => {
                this.enterRoom(item.id);
              }}>
              <i class={[style['room-item-status'], item.status && style['room-item-status-running']]}></i>
              <div class={style['room-item-data']} data-id={item.id} data-name={item.name}></div>
              <div class={style['room-item-content']}>
                <img src={roomSvg} alt='room' />
                <p>{item.name}</p>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  private renderAddRoomModel() {
    return (
      <van-dialog
        v-model={this.isAddModel}
        title='添加房间'
        showConfirmButton={false}
        closeOnClickOverlay
        class={viewsStyle['model']}>
        {this.renderAddForm()}
      </van-dialog>
    );
  }

  private renderAddForm() {
    return (
      <div class={viewsStyle['model-form']}>
        <van-field
          v-model={this.form.name}
          label='房间名称'
          colon
          placeholder='请输入房间名称'
          required
          center
          clearable
          error-message={''}
        />
        <div class={viewsStyle['model-form-submit']}>
          <van-button
            type='default'
            size='small'
            class={viewsStyle['touch']}
            on-click={() => {
              this.isAddModel = false;
            }}>
            取 消
          </van-button>
          <van-button
            size='small'
            color='#20a5df'
            class={this.form.name && viewsStyle['touch']}
            disabled={!this.form.name}
            on-click={this.submitAddRoom}>
            创 建
          </van-button>
        </div>
      </div>
    );
  }

  private enterRoom(room_id: string) {
    // this.$store.commit('update', { curRoom: room });
    this.$router.push({ name: 'room-detail', query: { room_id } });
  }

  private showAddModel() {
    if (this.isManager) {
      this.form.name = '';
      this.isAddModel = true;
    }
  }

  private submitAddRoom() {
    this.$socket.client.emit('create-room', this.form, (data: ICreateRoomResp) => {
      if (data.result) {
        this.$message.success(data.message);
        this.isAddModel = false;
        this.$nextTick(() => this.enterRoom(data.data.id));
      } else {
        this.$message.error(data.message);
      }
    });
  }

  private handleLongTag() {
    if (this.isManager) {
      Utils.bindLongTag(document.getElementById('room-list') as HTMLElement, (e: TouchEvent) => {
        const id = (e.target as HTMLElement).dataset.id;
        const name = (e.target as HTMLElement).dataset.name;
        if (!id) {
          return;
        }
        Dialog.confirm({
          message: `删除后数据将无法恢复，确定删除${name}房间以及相应配置吗？`
        }).then(() => {
          this.$socket.client.emit('delete-room', id, (res: IResponse) => {
            if (res.result) {
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          });
        });
      });
    } else {
      Utils.unbindLongTag(document.getElementById('room-list') as HTMLElement, () => {
        console.log('removeEventListener');
      });
    }
  }
}
